import axios from 'axios';
import config from '../../public/config';
import { ElMessage } from 'element-plus';
axios.defaults.timeout = 5000;
axios.defaults.withCredentials = true;

// 修改响应头配置
axios.defaults.headers.common['Authorization'] = localStorage.getItem('token');
// axios.defaults.headers.post['Content-Type'] = 'application/json';
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
axios.defaults.headers.common['Access-Control-Allow-Origin'] = '*';
//基础url
axios.defaults.baseURL=config.baseUrl
//拦截器
axios.interceptors.response.use(
  response =>{
    if(response.status == 200 || response.code == 200 || response){
      return Promise.resolve(response);
    }else{
      return Promise.reject(response);
    }
  },
  error =>{
    if(error.response && error.response.status){
      switch(error.response.status){
        case 404:
          ElMessage.error('请求资源不存在');
          break;
        case 500:
          ElMessage.error('服务器错误');
          break;
        case 502:
          ElMessage.error('服务器错误');
          break;
        case 401:
          ElMessage.error("登录已过期或者您还没有登陆，请重新登录");
          localStorage.clear();
          break;
        default:
          ElMessage.error(`其他错误：${error.response.status}`);
      }
      return Promise.reject(error.response);
    }
    return Promise.reject(error); // 处理没有response的情况
  }
);

// 添加请求拦截器
axios.interceptors.request.use(
  config => {
    const token = localStorage.getItem('token');

    if (token) {
      config.headers['Authorization'] = token;
      // console.log('请求头:', config.headers);
    } else {
      console.log('没有找到token');
    }
    
    return config;
  },
  error => {
    console.error('请求拦截器错误:', error);
    return Promise.reject(error);
  }
);

//get
export function get(url,params={}){
    return new Promise((resolve,reject) =>{
      axios.get(url,{params})
      .then(response =>{
        resolve(response.data)
      })
      .catch(err =>{
        reject(err)
      })
    })
}

//post
export function post(url,data={}){
  return new Promise((resolve,reject) =>{
    axios.post(url,data)
    .then(response =>{
      resolve(response.data)
    })
    .catch(err =>{
      reject(err)
    })
  })
}

